﻿from django import forms
from django.forms.models import modelformset_factory, BaseModelFormSet
from userprofile.models import UserProfile
from geography.models import L0Object, L1Object, L2Object, L34Object, Place

class PlaceForm(forms.ModelForm):
    name = forms.CharField(label=u'Название', required=False, widget=forms.TextInput(attrs={'autocomplete': 'off', 'class': 'place_name'}))
    name_hidden = forms.CharField(required=False, widget=forms.HiddenInput(attrs={'autocomplete': 'off', 'class': 'place_h'}))
    L34Object_name = forms.CharField(label=u'Город/поселок/деревня', required=False, widget=forms.TextInput(attrs={'autocomplete': 'off', 'class': 'place_L34Object'}))
    L34Object_hidden = forms.CharField(required=False, widget=forms.HiddenInput(attrs={'autocomplete': 'off', 'class': 'L34_h'}))
    
    
    def __init__(self, *args, **kwargs):
        super(PlaceForm, self).__init__(*args, **kwargs)
        if self.instance is not None:
            l34_name = self.instance.L34Object.name if self.instance.L34Object is not None else ''
            l34 = str(self.instance.L34Object.id) if self.instance.L34Object is not None else '0'
            l2 = str(self.instance.L2Object.id) if not self.instance.L2Object in [None, 0] else '0'
            l1 = str(self.instance.L1Object.id) if not self.instance.L1Object in [None, 0] else '0'
            self.fields['L34Object_name'].initial = l34_name
            self.fields['L34Object_hidden'].initial = l34+';'+l2+';'+l1
            
    def clean(self):
        data = self.cleaned_data.get('L34Object_hidden', None)
        id = self.cleaned_data.get('name_hidden', None)
        if data != u'':
            (L34, L2, L1) = tuple([int(data.split(';')[i] if data.split(';')[i]<>'null' else 0) for i in range(0,3)])
            self.cleaned_data['L1Object'] = L1Object.objects.get(pk=L1) if L1!=0 else None
            self.cleaned_data['L2Object'] = L2Object.objects.get(pk=L2) if L2!=0 else None
            self.cleaned_data['L34Object_name'] = L34Object.objects.get(pk=L34) if L34!=0 else None
        if id != u'':
            self.instance = Place.objects.get(pk=int(id))
        return self.cleaned_data
    
    def save(self, *args, **kwargs):
        data = self.cleaned_data
        m = super(PlaceForm, self).save(commit=False)
        try:
            m.L1Object = data.get('L1Object', None)
            m.L2Object = data.get('L2Object', None)
            m.L34Object = data.get('L34Object_name', None)
        except:
            pass
        if kwargs.get('commit', True):
            m.save()
        return m
        
    class Meta:
        model = Place
        fields = ('name', 'L34Object_hidden', 'L0Object', 'L34Object_name', 'street' ,'house_num', 'apartament_num', 'place_type')
        
    class Media:
    	js = ('js/ajax_place.js', )

class BasePlaceFormSet(BaseModelFormSet):
    def save_existing_objects(self, commit=True):
        self.changed_objects = []
        self.deleted_objects = []
        if not self.get_queryset():
            return []
        saved_instances = []
        for form in self.initial_forms:
            pk_name = self._pk_field.name
            raw_pk_value = form._raw_value(pk_name)
            pk_value = form.fields[pk_name].clean(raw_pk_value)
            pk_value = getattr(pk_value, 'pk', pk_value)
            obj = self._existing_object(pk_value)
            if self.can_delete:
                raw_delete_value = form._raw_value(DELETION_FIELD_NAME)
                should_delete = form.fields[DELETION_FIELD_NAME].clean(raw_delete_value)
                if should_delete:
                    self.deleted_objects.append(obj)
                    continue
            if form.has_changed():
                self.changed_objects.append((obj, form.changed_data))
                saved_instances.append(self.save_existing(form, obj, commit=commit))
                if not commit:
                    self.saved_forms.append(form)
        return saved_instances

    def save_new_objects(self, commit=True):
        self.new_objects = []
        for form in self.extra_forms:
            if not form.has_changed() and not form.is_bound():
                continue
            if self.can_delete:
                raw_delete_value = form._raw_value(DELETION_FIELD_NAME)
                should_delete = form.fields[DELETION_FIELD_NAME].clean(raw_delete_value)
                if should_delete:
                    continue
            self.new_objects.append(self.save_new(form, commit=commit))
            if not commit:
                self.saved_forms.append(form)
        return self.new_objects
    

PlaceFormSet = modelformset_factory(Place, form=PlaceForm, formset=BaseModelFormSet, max_num=0, extra=1, can_delete=True)